﻿using AutoMapper;
using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.WriteAPI.Applications.Commands.Users;
using MD5Hash;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.Meeting.WriteAPI.Applications.CommandHandlers.Users
{
    public class UpdUserCommandHandler:IRequestHandler<UpdUserCommand,APIResult<int>>
    {
        IMapper mapper;
        IBaseRepository<User> uRep;
        ILogger<UpdUserCommandHandler> logger;
        public UpdUserCommandHandler(IBaseRepository<User> uRep, ILogger<UpdUserCommandHandler> logger, IMapper mapper)
        {
            this.uRep = uRep;
            this.logger = logger;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(UpdUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var userToUpdate = await uRep.GetByIdAsync(request.Data.UserId);

                //if (userToUpdate == null)
                //{
                //    return new APIResult<int>
                //    {
                //        Code = StatusEnumCode.Fail,
                //        Message = "用户不存在",
                //        Data = 0
                //    };
                //}

                //mapper.Map(request.Data, userToUpdate);

                //if (request.Data.UserPwd != null && userToUpdate.UserPwd != request.Data.UserPwd)
                //{
                //    userToUpdate.UserPwd = request.Data.UserPwd.GetMD5();
                //}

                var list = await uRep.UpdAsync(request.Data);

                return new APIResult<int>
                {
                    Code = StatusEnumCode.Ok,
                    Message = "修改用户成功",
                    Data = list
                };
            }
            catch (Exception ex)
            {
                logger.LogError("修改用户失败", ex);
                throw;
            }
        }
    }
}
